package com.cjhstudy.mall.controller;

import com.cjhstudy.mall.consts.MallConst;
import com.cjhstudy.mall.form.UserLoginForm;
import com.cjhstudy.mall.form.UserRegisterForm;
import com.cjhstudy.mall.pojo.User;
import com.cjhstudy.mall.service.IUserService;
import com.cjhstudy.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Objects;

import static com.cjhstudy.mall.enums.ResponseEnum.PARAM_ERROR;

/**
 * @author: phil
 * @ProjectName: mall
 * @Date: 2021/12/8
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 1、如果前端的是用 “x-www-form-urlencoded” 来访问 URL 的话，那么我们就用 @RequestParam String username 来接收
     * 也可以自定义后面的接收变量但是得加上 @RequestParam(value ="username") String name 即可
     *
     * 2、如果前端是使用 row -- JSON 的格式来访问 URL 的话，那么我们就用 @RequestBody  User user 来规定就可以
     * @param userForm
     */

    /**
     * 用户注册
     * @param userForm 用户注册表
     * @param bindingResult 校验
     * @return 返回成功失败
     */
    @PostMapping("/user/register")
    public ResponseVo register(@Valid @RequestBody UserRegisterForm userForm,
                               BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            log.error("注册提交的参数有误,{} {}",
                    Objects.requireNonNull(bindingResult.getFieldError()).getField(),
                    bindingResult.getFieldError().getDefaultMessage());
            return ResponseVo.error(PARAM_ERROR,bindingResult);
        }
        log.info("username={}",userForm.getUsername());
        User user = new User();
        BeanUtils.copyProperties(userForm,user);

        return userService.register(user);
//        return ResponseVo.error(ResponseEnum.NEED_LOGIN);
    }


    /**
     * 用户登录
     * @param userLoginForm 用户登录表
     * @param bindingResult 用校验
     * @param session 用户登录的session
     * @return
     */
    @PostMapping("/user/login")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm,
                                  BindingResult bindingResult, HttpSession session){
        if (bindingResult.hasErrors()){
            return ResponseVo.error(PARAM_ERROR,bindingResult);
        }
        ResponseVo<User> userResponseVo = userService.login(userLoginForm.getUsername(), userLoginForm.getPassword());

        //设置Session
        session.setAttribute(MallConst.CURRENT_USER,userResponseVo.getData());

        return userResponseVo;
    }

    /**
     * 返回用户的信息
     * @param session 用户登录的session
     * @return
     */
    //session 存放在Redis中，改进版: token+redis
    @GetMapping("/user")
    public ResponseVo<User> userInfo(HttpSession session){
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success(user);
    }


    /**
     * 用户登出
     * @param session 用户登录的session
     * @return
     */
    @PostMapping("/user/logout")
    public ResponseVo logout(HttpSession session){
        log.info("/user/logout sessionId={}",session.getId());
        session.removeAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success();
    }

}
